﻿#include "PatrolServer.h"
#include <QtWidgets/QApplication>
#include <QSplashScreen>
#include <QTextCodec>
#include "Common.h"



// 添加本地环境变量
void setDirPath()
{
	QString strDirPath = QCoreApplication::applicationDirPath() + "/syslib/";
	QDir dir(strDirPath);
	QFileInfoList fileInfoList = dir.entryInfoList(QDir::Files | QDir::NoDotAndDotDot | QDir::Dirs);

	QString envPath = qgetenv("PATH");
	// 首先在 syslib 根目录下设置环境变量
	envPath += QDir::toNativeSeparators(strDirPath).prepend(';');
	for (int i = 0; i < fileInfoList.size(); i++)
	{
		// 遍历所有目录，并设置环境变量
		QString str = fileInfoList[i].filePath();
		envPath += QDir::toNativeSeparators(str).prepend(';');
	}
	qputenv("PATH", envPath.toStdString().c_str());
}

//#include <io.h>
#include <fcntl.h>  
#include <iostream>  
//#include <windows.h>



int main(int argc, char* argv[])
{
	// 高分屏缩放支持
	QApplication::setAttribute(Qt::AA_EnableHighDpiScaling);

	// 高分屏缩放策略设置
	QApplication::setHighDpiScaleFactorRoundingPolicy(Qt::HighDpiScaleFactorRoundingPolicy::PassThrough);

	//std::freopen("out.txt", "w", stdout);


	QApplication a(argc, argv);

	QSharedMemory memory(QCoreApplication::applicationName());

	if (!memory.create(1))
	{
		QStringList arguments = QCoreApplication::arguments();

		if (arguments.size() == 1)
		{
			QMessageBox* pMsgBox = new QMessageBox(QMessageBox::Warning, "PatrolServer  ( 5 )秒后自动取消", "软件已经启动，不允许重复打开");
			QTimer::singleShot(5000, pMsgBox, SLOT(accept()));
            memory.attach();
            memory.detach();
			pMsgBox->exec();
			delete pMsgBox;
		}
		qApp->quit();
		return 0;
	}

	// 添加本地环境变量
	setDirPath();


	QString imageText = "AI 巡检系统";
	QImage image(800, 600, QImage::Format_RGB888);
	image.fill(QColor(125, 125, 125));
	QPainter painter(&image);
	//改变画笔和字体
	QPen pen = painter.pen();
	pen.setColor(QColor(20, 20, 20));

	painter.setPen(pen);

	QFont font;
	//设置显示字体的大小
	font.setPixelSize(60);

	QFontMetrics fm(font);
	int charWidth = fm.width(imageText);
	charWidth = fm.boundingRect(imageText).width();



	painter.setFont(font);

	//将Hello写在Image的中心
	painter.drawText(image.rect(), Qt::AlignCenter, imageText);


	QPixmap pix(QPixmap::fromImage(image));
	pix = pix.scaled(640, 360, Qt::KeepAspectRatio, Qt::SmoothTransformation);
	QSplashScreen splash(pix);

	Qt::Alignment topRight = Qt::AlignLeft | Qt::AlignBottom;//先设置一个格式
	splash.showMessage("系统加载中.....(更新模型后，首次运行需要较长时间)", topRight, Qt::red);//显示文字示例
	splash.show();

	// linux 下，加载页面可能不显示
	QEventLoop loop;
	QTimer::singleShot(200, &loop, SLOT(quit()));
	loop.exec(); // 开始事件循环，直到200毫秒后退出

    a.processEvents();

	PatrolServer w;
	//w.setMaximumSize(QSize( 800,600));
	w.setWindowState(Qt::WindowMaximized);
	w.show();
	splash.finish(&w);

	bool ok = false;
	ok = a.exec();
	memory.attach();
	memory.detach();

	return ok;
}
